﻿using SpiderPlatform.Entity;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks.Schedulers;

namespace SpiderPlatform.Service
{
    class FreshGoGoService
    {
         public void doWork()
        {
            List<FrechProduct> all = new List<FrechProduct>();
            var cateList = GetCategory();
            Logger.Info($"共获得{cateList.Count}个分类");            
            foreach (var item in cateList)
            {
                Logger.Info($"处理{item.CategoryName}");
                var cateProducts = GetProduct(item);
                Logger.Info($"处理{item.CategoryName}完成===》{cateProducts.Count}个商品");
                all.AddRange(cateProducts);
            }
            Logger.Info($"全部拉取完成，共{all.Count}个商品");
            TaskFactory fac = new TaskFactory(new LimitedConcurrencyLevelTaskScheduler(20));
            List<Task> taskList = new List<Task>();
            foreach (var prd in all)
            {
                var task=fac.StartNew(() =>
                {
                    GetDetail(prd);
                    Logger.Info($"{prd.Name}===>详情完成");
                });
                taskList.Add(task);
            }
            Task.WaitAll(taskList.ToArray());
            Logger.Info($"开始导出");
            var data = new StringBuilder("sku,分类,品名,副标题,规格,价格,会员价,单价,是否售罄,Tag,天天低价,优质,评价数,评分,月销量"+Environment.NewLine);
            foreach (var item in all)
            {
                data.AppendLine($"{item.SKU},{item.CateGoryName},{item.Name},{item.Title},{item.Summary},{item.Price}," +
                    $"{item.PlusPprice},{item.ValuePackPrice},{item.IsSellOut},{item.Tag},{item.IsLower},{item.IsGood}," +
                    $"{item.Reviews},{item.Star},{item.OrderCount}");
            }
            if (System.IO.File.Exists("fresh.csv"))
            {
                System.IO.File.Delete("fresh.csv");
            }
            System.IO.File.AppendAllText("fresh.csv",data.ToString());
            Logger.Info("导出完成");
        }


        List<FrechProduct> GetProduct(FreshCategoryEntity cate) {
            List<FrechProduct> productList = new List<FrechProduct>();
            HttpClient client = new HttpClient();
            var res = client.GetAsync($"https://www.freshgogo.com/interface/catelog/getHomeCateDetailById?cid={cate.CatrgoryID}&homearea_id=1").Result;
            var str = res.Content.ReadAsStringAsync().Result;
            var result = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(str);
            if (result.status==1)
            {
                foreach (var item in result.data)
                {
                    var prd = new FrechProduct
                    {
                        SKU = item.id,
                        Name = item.name,
                        CateGoryName = cate.CategoryName,
                        OrderCount = item.order_quantity,
                        IsSellOut = item.is_sell_out,
                        Price = item.price,
                        PlusPprice = item.plus_price,
                        Star = item.star_avg,
                        Reviews = item.comment_num,
                        Summary = item.summary,
                        Title = item.adv_str,
                        ValuePackPrice = item.value_pack_price,
                        Tag = item.labels.Count > 0 ? item.labels[0].name : ""
                    };              
                    productList.Add(prd);
                }
            }
            return productList;
        }

        FrechProduct GetDetail(FrechProduct prd)
        {
            HttpClient client = new HttpClient();
            var res = client.GetAsync($"https://www.freshgogo.com/interface/Commodity?id={prd.SKU}&user_id=&homearea_id=1").Result;
            var str = res.Content.ReadAsStringAsync().Result;
            var result = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(str);
            if (result.status==1)
            {
                prd.OrderCount = result.data.month_sell_pre;
                prd.Star = result.data.star;
            }
            return prd;
        }

        List<FreshCategoryEntity> GetCategory()
        {
            List<FreshCategoryEntity> cateList = new List<FreshCategoryEntity>();
            HttpClient client = new HttpClient();
            //var postData = new
            //{
            //    limit = 100,
            //    page = page,
            //    lang = "zh",
            //    t = 4
            //};
            //HttpContent httpContent = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(postData));
            ////设置Http的内容标头
            //httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json") { CharSet = "utf-8" };
            var res = client.GetAsync("https://www.freshgogo.com/interface/catelog/list").Result;
            var str = res.Content.ReadAsStringAsync().Result;
            var result = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(str);
            if (result.status==1)
            {
                foreach (var item in result.data)
                {
                    cateList.Add(new FreshCategoryEntity {
                        CatrgoryID=item.id,
                        CategoryName=item.name
                    });
                }
            }
            return cateList;
        }
    }
}
